package com.ifudata.dataexpert.controller;

import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.ifudata.dataexpert.constants.MktConstants;
import com.ifudata.dataexpert.constants.SmsConstants;
import com.ifudata.dataexpert.controller.param.MktApproveRequest;
import com.ifudata.dataexpert.controller.param.MktGetDataRequest;
import com.ifudata.dataexpert.controller.param.MktOperationRequest;
import com.ifudata.dataexpert.controller.param.MktParamRequest;
import com.ifudata.dataexpert.controller.param.MktResultForecastRequest;
import com.ifudata.dataexpert.controller.param.MktSearchRequest;
import com.ifudata.dataexpert.controller.param.MktSendOneSmsRequest;
import com.ifudata.dataexpert.controller.param.MktSubmitRequest;
import com.ifudata.dataexpert.model.ResultMap;
import com.ifudata.dvp.base.exception.BusinessException;
import com.ifudata.dvp.base.vo.BaseResponse;
import com.ifudata.dvp.base.vo.PageInfoResponse;
import com.ifudata.dvp.base.vo.RequestHeader;
import com.ifudata.dvp.base.vo.ResponseHeader;
import com.ifudata.dvp.mkt.api.activity.interfaces.IMktActivitySV;
import com.ifudata.dvp.mkt.api.activity.param.MktActivityApproveRequest;
import com.ifudata.dvp.mkt.api.activity.param.MktActivityOperationRequest;
import com.ifudata.dvp.mkt.api.activity.param.MktActivityQueryRequest;
import com.ifudata.dvp.mkt.api.activity.param.MktActivityVo;
import com.ifudata.dvp.mkt.api.marketing.interfaces.IMarketingConfigSV;
import com.ifudata.dvp.mkt.api.marketing.param.MktSubmitAndApproveRequest;
import com.ifudata.dvp.mkt.api.policy.interfaces.IPolicyMatchingSV;
import com.ifudata.dvp.mkt.api.policy.param.PolicyEnforcementRequest;
import com.ifudata.dvp.mkt.api.policy.param.ResultForecastResponse;
import com.ifudata.dvp.mkt.api.policy.param.UserMatchingAppResponse;
import com.ifudata.dvp.mkt.api.policy.param.UserMatchingRequest;
import com.ifudata.dvp.mkt.api.task.interfaces.IMktTaskSV;
import com.ifudata.dvp.mkt.api.task.param.MktSmsMsRequest;
import com.ifudata.dvp.om.api.busi.interfaces.IRptOmGetDataSV;
import com.ifudata.dvp.om.api.busi.param.RptOmGetDataRequest;
import com.ifudata.dvp.om.api.busi.param.RptOmGetDataResponse;
import com.ifudata.dvp.sdk.dubbo.util.DubboConsumerFactory;
import com.ifudata.dvp.sdk.util.DateUtil;
import com.ifudata.dvp.sdk.util.StringUtil;
import com.ifudata.dvp.sdk.util.SysStaffCacheUtil;

/**
 *
 * @Author libing 
 * @Description app controller
 * @Date 2018-10-18
 * @Time 17:12
 */
@RestController
@RequestMapping("/mkt")
@Scope(value = "prototype")
public class MktController {
	private static final Logger log = LoggerFactory.getLogger(MktController.class);
	
	/**
	 * 查询
	 * @param request    activityStatus 1 待审批 4已开始 8已关闭
	 * @param searchRequest
	 */
	@PostMapping("/searchActivity")
	@Produces(MediaType.APPLICATION_JSON)
	@RequiresRoles(logical = Logical.OR, value = {"user"})
	@ResponseBody
	public ResultMap search(@RequestBody MktSearchRequest searchRequest,HttpServletRequest request) {
		log.debug("请求/mkt/searchActivity 参数:{}",searchRequest.toString());
		ResultMap resultMap = new ResultMap(true);
		RequestHeader header = resultMap.getRequestHeader(request);
		DecimalFormat df = new DecimalFormat("0.00");
		// 业务参数
		String activityName = searchRequest.getActivityName();
		String startTime = searchRequest.getStartTime();
		String endTime = searchRequest.getEndTime();
		String activityStatus = searchRequest.getActivityStatus();
		// 展示参数
		String sEcho = "1";// 固定标示，原封给返回参数
		//String sortColInx = "2";// 排序列序号
		String sortType = "desc";// 排序方式：desc-asc
		String sortColName = "createTime";// 排序列名称
		String displayStart = "0";// 分页开始位
		String displayLength = "10";// 每页返回行数

		/* 查询数据 */
		IMktActivitySV sv = DubboConsumerFactory.getService(IMktActivitySV.class);
		MktActivityQueryRequest req = new MktActivityQueryRequest();
		req.setRequestHeader(header);
		
		// 业务参数
		if ( !StringUtil.isBlank(activityName) ) req.setActivityName(activityName);
		if ( !StringUtil.isBlank(startTime) ) req.setStartTime(Timestamp.valueOf(startTime + " 00:00:00"));
		if ( !StringUtil.isBlank(endTime) ) req.setEndTime(Timestamp.valueOf(endTime + " 23:59:59"));
		if ( !StringUtil.isBlank(activityStatus) ) req.setActivityStatus(activityStatus);

		// 展示参数
		req.setPageSize(Integer.parseInt(displayLength));
		req.setStartIndex(Integer.parseInt(displayStart));
		req.setSortCol(sortColName);
		req.setSortType("desc".equals(sortType) ? 1 : 0);// 0升序1降序

		PageInfoResponse<MktActivityVo> result = sv.queryMktActivity(req);
		//List<String> approveActivityType = getActivityApproveCategory(request);
		
		// 拼接返回参数
		JSONObject o = new JSONObject();
		o.put("draw", sEcho);
		if (result.getResponseHeader().isSuccess()) {
			o.put("recordsTotal", result.getCount());
			o.put("recordsFiltered", result.getCount());
			JSONArray data = new JSONArray();
			// 开始翻译
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			result.getResult().forEach(list -> {
				JSONObject obj = JSON.parseObject(JSON.toJSONString(list));
				String activityNameResult = list.getActivityName();
				if (!StringUtil.isBlank(activityNameResult)) {
					String firstChar = activityNameResult.substring(0,1);
					obj.put("activityNameTable", "<i class='flag-first'>"+firstChar+"</i><span class='flag-activity-name'>"+activityNameResult+"</span><span style = 'background:"+ MktConstants.getActivityStatusColor(list.getStatus()) +";' class='flag-status'>"+MktConstants.getActivityStatusName(list.getStatus())+"</span>");
				} else {
					obj.put("activityNameTable", "-");
				}
				
				if ( list.getStartTime()!=null&&list.getEndTime()!=null ) {
					obj.put("activityTime", sdf.format(list.getStartTime())+"~"+sdf.format(list.getEndTime()));
				} else {
					obj.put("activityTime", "-");
				}
				if (list.getCreateTime() != null) {
					obj.put("createTime", sdf.format(list.getCreateTime()));
				} else {
					obj.put("createTime", "-");
				}
				if (list.getActivityOverTime() != null) {
					obj.put("activityOverTime", sdf.format(list.getActivityOverTime()));
				} else {
					obj.put("activityOverTime", "-");
				}
				if( list.getStaffId()!=null ){
					String name = SysStaffCacheUtil.getStaffName(Long.parseLong(list.getStaffId()));
					obj.put("staffName", name);
				}
				if( list.getIsftp().equals("1") ){
					obj.put("isFtp", "触发");
				}else{
					obj.put("isFtp", "群发");
				}
				
				//策略类型
				obj.put("policeType", "价值提升");

				obj.put("activityStatusName", MktConstants.getActivityStatusName(list.getStatus()));
				
				obj.put("count", "总计&nbsp;"+(list.getSendAllCnt()==null?"-":String.valueOf(list.getSendAllCnt()))+"<br>"
						+ "发送&nbsp;"+(list.getSendSuccessCnt()==null?"-":String.valueOf(list.getSendSuccessCnt()))+"/"
						+ (list.getSendFailCnt()==null?"-":String.valueOf(list.getSendFailCnt()))+"<br>"
						+ "办理&nbsp;"+(list.getTransactSuccessCnt()==null?"-":String.valueOf(list.getTransactSuccessCnt()))+"/"
						+ (list.getTransactFailCnt()==null?"-":String.valueOf(list.getTransactFailCnt()))
						);
				
				if( list.getSendSuccessCnt()==null||list.getSendSuccessCnt()<=0 ){
					obj.put("successRate", "-");
				}else{
					obj.put("successRate", df.format(((double)list.getTransactSuccessCnt()/list.getSendSuccessCnt())*100));
				}
				
				// 判断是否有审批权限
				/*if(approveActivityType.contains(list.getActivityType())){
					obj.put("hasApproveBtn", true);
				}else{
					obj.put("hasApproveBtn", false);
				}*/
				obj.put("hasApproveBtn", true);
				
				// 判断是否为当前登录用户创建的
				/*if( header.getStaffId().toString().equals(list.getStaffId()) ){
					obj.put("own", true);
				}else{
					obj.put("own", false);
				}*/
				obj.put("own", true);
				
				data.add(obj);
			});
			o.put("data", data);
		} else {
			o.put("recordsTotal", 0);
			o.put("recordsFiltered", 0);
			o.put("data", new JSONArray());
		}
		resultMap.success().message(SmsConstants.ResMsg.SET_SUCCESS).dataJson(o);
		return  resultMap;
	}
	
	
	
	/**
	 * 审核
	 * @param approveRequest
	 * @param request
	 * @param response
	 * @return
	 */
	@PostMapping("/approve")
	@Produces(MediaType.APPLICATION_JSON)
	@RequiresRoles(logical = Logical.OR, value = {"user"})
	@ResponseBody
	public ResultMap approve(@RequestBody MktApproveRequest approveRequest, HttpServletResponse response,HttpServletRequest request) {
		log.debug("请求/mkt/approve 参数:{}",approveRequest.toString());
		IMktActivitySV sv = DubboConsumerFactory.getService(IMktActivitySV.class);
		MktActivityApproveRequest req = new MktActivityApproveRequest();
		ResultMap resultMap = new ResultMap(true);
		RequestHeader header = resultMap.getRequestHeader(request);
		req.setRequestHeader(header);
		
		if( StringUtil.isBlank(approveRequest.getRelId()) ) throw new BusinessException("策略id为空");
		req.setRelId(Long.parseLong(approveRequest.getRelId()));
		
		if( approveRequest.getApprove().equals("1") ) {//审批通过
			req.setActivityStatus(MktConstants.ActivityStatus.STATUS_APPROVE_SUCCESS);
		}else{//审批失败
			req.setActivityStatus(MktConstants.ActivityStatus.STATUS_APPROVE_FAIL);
		}
		req.setApproveOpinion(approveRequest.getOpinion());
		req.setApproveTime(DateUtil.getSysDate());
		BaseResponse rep = sv.approve(req);
		JSONObject object = new JSONObject();
		// 拼接返回参数
		if (rep.getResponseHeader().isSuccess()) {
			object.put("data", SmsConstants.ResMsg.SET_SUCCESS);
			resultMap.success().message(SmsConstants.ResMsg.SET_SUCCESS).dataJson(object);
		} else {
			resultMap.fail().message(rep.getResponseHeader().getResultMessage());
		}
		return  resultMap;
	}
	
	
	/**
	 * 关闭,删除,暂停
	 * @param activityId
	 * @param request
	 * @param response
	 * @return
	 */
	@PostMapping("/operation")
	@Produces(MediaType.APPLICATION_JSON)
	@RequiresRoles(logical = Logical.OR, value = {"user"})
	@ResponseBody
	public ResultMap operation(@RequestBody MktOperationRequest operationRequest,HttpServletRequest request, HttpServletResponse response) {
		log.debug("请求/mkt/operation 参数:{}",operationRequest.toString());
		IMktActivitySV sv = DubboConsumerFactory.getService(IMktActivitySV.class);
		MktActivityOperationRequest req = new MktActivityOperationRequest();
		ResultMap resultMap = new ResultMap(true);
		RequestHeader header = resultMap.getRequestHeader(request);
		req.setRequestHeader(header);
		if( StringUtil.isBlank(operationRequest.getRelId()) ) throw new BusinessException("策略id为空");
		req.setRelId(Long.parseLong(operationRequest.getRelId()));
		
		if( StringUtil.isBlank(operationRequest.getStatus()) ) throw new BusinessException("状态为空");
		req.setStatus(operationRequest.getStatus());
		JSONObject object = new JSONObject();
		BaseResponse rep = sv.operation(req);
		if (rep.getResponseHeader().isSuccess()) {
			object.put("data", SmsConstants.ResMsg.SET_SUCCESS);
			resultMap.success().message(SmsConstants.ResMsg.SET_SUCCESS).dataJson(object);
		} else {
			resultMap.fail().message(rep.getResponseHeader().getResultMessage());
		}
		return  resultMap;
	}
	
	/**
	 * 第一步 用户筛选
	 * update libing
	 * @param request
	 * @param response
	 * @return
	 * @author libing
	 */
	@PostMapping("/userMatching")
	@Produces(MediaType.APPLICATION_JSON)
	@RequiresRoles(logical = Logical.OR, value = {"user"})
	@ResponseBody
    public ResultMap userMatching(@RequestBody MktParamRequest paramRequest,HttpServletRequest request) {
		log.debug("请求/mkt/userMatching 参数:{}",paramRequest.toString());
		JSONObject object = new JSONObject();
		ResultMap resultMap = new ResultMap(true);
		String policyType = paramRequest.getType();//type GW 固网 YW 移网
        IPolicyMatchingSV sv = DubboConsumerFactory.getService(IPolicyMatchingSV.class);
        UserMatchingAppResponse rep = sv.policyMatchingApp(policyType);
        ResponseHeader response = rep.getResponseHeader();
        if (rep.getResponseHeader().isSuccess()) {
        	JSONArray data = JSONArray.parseArray(JSONArray.toJSONString(rep.getPolicyMind(),SerializerFeature.WriteMapNullValue,SerializerFeature.WriteDateUseDateFormat));
			object.put("data", data);
			resultMap.success().message(SmsConstants.ResMsg.SET_SUCCESS).dataJson(object);
		} else {
			resultMap.fail().message(response.getResultMessage());
		}
		return  resultMap;
    }
	
	/**
     * 第二步 产品匹配
     * update libing
     * @param request
     * @param response
     * @return
     * @author libing
     */
	@PostMapping("/policyMatching")
	@Produces(MediaType.APPLICATION_JSON)
	@RequiresRoles(logical = Logical.OR, value = {"user"})
	@ResponseBody
	public ResultMap policyMatching(@RequestBody MktParamRequest paramRequest, HttpServletRequest request) {
		log.debug("请求/mkt/policyMatching 参数:{}",paramRequest.toString());
		JSONObject object = new JSONObject();
		ResultMap resultMap = new ResultMap(true);
		if( paramRequest.getId()==null ) throw new BusinessException("参数为空");
		String policyType = paramRequest.getType();
		IPolicyMatchingSV sv = DubboConsumerFactory.getService(IPolicyMatchingSV.class);
		UserMatchingRequest req = new UserMatchingRequest();
		req.setPolicyType(policyType);
		List<String> listId = new ArrayList<String>();
		listId.add(paramRequest.getId());
		req.setGroupIdList(listId);
		UserMatchingAppResponse rep = null;
		rep = sv.matchingPeriodicityApp(req);
		ResponseHeader response = rep.getResponseHeader();
        if (response.isSuccess()) {
        	JSONArray data = JSONArray.parseArray(JSONArray.toJSONString(rep.getPolicyMind(),SerializerFeature.WriteMapNullValue,SerializerFeature.WriteDateUseDateFormat));
			object.put("data", data);
			resultMap.success().message(SmsConstants.ResMsg.SET_SUCCESS).dataJson(object);
		} else {
			resultMap.fail().message(response.getResultMessage());
		}
		return  resultMap;
	}
	
	/**
     * 第三步 结果预测
     * @param request
     * @return
     */
	@PostMapping("/resultForecast")
	@Produces(MediaType.APPLICATION_JSON)
	@RequiresRoles(logical = Logical.OR, value = {"user"})
	@ResponseBody
    public ResultMap resultForecast(@RequestBody MktResultForecastRequest resultForecastRequest) {        
		log.debug("请求/mkt/resultForecast 参数:{}",resultForecastRequest.toString());
		JSONObject object = new JSONObject();
		ResultMap resultMap = new ResultMap(true);
        PolicyEnforcementRequest enforcementRequest = new PolicyEnforcementRequest();
        enforcementRequest.setProductList(resultForecastRequest.getProducts());////p_policyId_productId|limt
    	IPolicyMatchingSV sv = DubboConsumerFactory.getService(IPolicyMatchingSV.class);
    	ResultForecastResponse rep = sv.resultForecastPeriodicity(enforcementRequest);
    	ResponseHeader response = rep.getResponseHeader();
        if (response.isSuccess()) {
			object.put("data", JSON.parseObject(JSON.toJSONString(rep)));
			resultMap.success().message(SmsConstants.ResMsg.SET_SUCCESS).dataJson(object);
		} else {
			resultMap.fail().message(response.getResultMessage());
		}
		return  resultMap;
    }
	
	
	/**
     * 发送测试短信
     * update libing
     * @param request
     * @param response
     * @return
     */
	@PostMapping("/sendOneSms")
	@Produces(MediaType.APPLICATION_JSON)
	@RequiresRoles(logical = Logical.OR, value = {"user"})
	@ResponseBody
    public ResultMap sendOneSms(@RequestBody MktSendOneSmsRequest resultForecastRequest) {
		log.debug("请求/mkt/sendOneSms 参数:{}",resultForecastRequest.toString());
		JSONObject object = new JSONObject();
		ResultMap resultMap = new ResultMap(true);
        MktSmsMsRequest smsMsRequest = new MktSmsMsRequest();
        if(!StringUtils.isEmpty(resultForecastRequest.getMsgContent()));
        smsMsRequest.setMsgContent(resultForecastRequest.getMsgContent());
        if(!StringUtils.isEmpty(resultForecastRequest.getPhone()));
        smsMsRequest.setPhone(resultForecastRequest.getPhone());
        IMktTaskSV mktTaskSV = DubboConsumerFactory.getService(IMktTaskSV.class);
        BaseResponse response = mktTaskSV.sendOneSms(smsMsRequest);
        ResponseHeader header = response.getResponseHeader();
        if (header.isSuccess()) {
			object.put("data", JSON.parseObject(JSON.toJSONString(response)));
			resultMap.success().message("发送成功").dataJson(object);
		} else {
			resultMap.fail().message("操作失败");
		}
		return  resultMap;
    }
	
	
	/**
     * 策略 提交审批
     * update libing
     * @param request
     * @param response
     * @return
     */
	@PostMapping("/submitAndApprove")
	@Produces(MediaType.APPLICATION_JSON)
	@RequiresRoles(logical = Logical.OR, value = {"user"})
	@ResponseBody
    public ResultMap submitAndApprove(@RequestBody MktSubmitRequest request, HttpServletRequest sreq) {
		log.debug("请求/mkt/submitAndApprove 参数:{}",request.toString());
		ResultMap resultMap = new ResultMap(true);
		RequestHeader header = resultMap.getRequestHeader(sreq);
		MktSubmitAndApproveRequest req = new MktSubmitAndApproveRequest();
    	req.setRequestHeader(header);
    	String isFtp = request.getIsFtp();
    	String acctMonth = request.getAcctMonth();
    	req.setAcctMonth(acctMonth);
        if(!StringUtils.isEmpty(isFtp))
            req.setIsFtp(isFtp);
    	req.setMktType(request.getMktType());
    	req.setSelectSql(request.getSelectSql());
    	req.setPriority(Integer.parseInt(request.getPriority()));
		req.setActivityName(request.getActivityName());
    	req.setActivityType(request.getActivityType());
    	if(!StringUtils.isEmpty(request.getActivityOverTime()))
            req.setActivityOverTime(DateUtil.getTimestamp(request.getActivityOverTime().trim()+" 23:59:59", DateUtil.DATETIME_FORMAT));
    	if(!StringUtils.isEmpty(request.getDayPushCnt()))
    	req.setDayPushCnt(Long.parseLong(request.getDayPushCnt()));
    	req.setDayPushTime(request.getDayPushTime());
    	if(!StringUtils.isEmpty(request.getStartTime()))
    		req.setStartTime(DateUtil.getTimestamp(request.getStartTime()+" 00:00:00", DateUtil.DATETIME_FORMAT));
    	if(!StringUtils.isEmpty(request.getEndTime()))
    		req.setEndTime(DateUtil.getTimestamp(request.getEndTime()+" 23:59:59", DateUtil.DATETIME_FORMAT));
        req.setActivityDesc(request.getActivityDesc());
        if(!StringUtils.isEmpty(request.getPolicyId()))
        req.setPolicyId(Long.parseLong(request.getPolicyId()));
        if(!StringUtils.isEmpty(request.getGroupId()))
        req.setGroupId(Long.parseLong(request.getGroupId()));
        if(!StringUtils.isEmpty(request.getFtpOperationname()))
            req.setFtpOperationname(request.getFtpOperationname());
        req.setProductList(request.getProuctSelectData());
        req.setPushChannelId(Long.parseLong(request.getPushChannelId()));
        req.setHsContent(request.getHsContent());
        if(!StringUtils.isEmpty(request.getChannelPushUserCnt()))
        	req.setChannelPushUserCnt(Long.parseLong(request.getChannelPushUserCnt()));
		
        IMarketingConfigSV sv = DubboConsumerFactory.getService(IMarketingConfigSV.class);
        BaseResponse response = sv.submitAndApprove(req);
        JSONObject object = new JSONObject();
		if (response.getResponseHeader().isSuccess()) {
			object.put("data", SmsConstants.ResMsg.SET_SUCCESS);
			resultMap.success().message(SmsConstants.ResMsg.SET_SUCCESS).dataJson(object);
		} else {
			resultMap.fail().message(response.getResponseHeader().getResultMessage());
		}
		return  resultMap;
    }
	
	@PostMapping("/getData")
	@Produces(MediaType.APPLICATION_JSON)
	@RequiresRoles(logical = Logical.OR, value = {"user"})
	@ResponseBody
	public ResultMap getData(@RequestBody MktGetDataRequest dataRequest,HttpServletRequest request) {
		ResultMap resultMap = new ResultMap(true);
		IRptOmGetDataSV sv = DubboConsumerFactory.getService(IRptOmGetDataSV.class);
		RptOmGetDataRequest req = new RptOmGetDataRequest();
		req.setKey(dataRequest.getSqlKey());
		Map<String, String> param = new HashMap<String, String>();
		param.put("${SELECTED}", "YW");
		req.setMap(param);
		RptOmGetDataResponse rep = sv.queryDataMaxDateById(req);
		JSONObject json = new JSONObject();
		List<List<String>> list = rep.getResult();
		json.put("today", rep.getMonth());
		if ( list!=null&&list.size()>0 ) {
			json.put("data_yw", JSONArray.parseArray(JSONArray.toJSONString(list)));
		}
		param.put("${SELECTED}", "GW");
		req.setMap(param);
		rep = sv.queryDataMaxDateById(req);
		list = rep.getResult();
		if ( list!=null&&list.size()>0 ) {
			json.put("data_gw", JSONArray.parseArray(JSONArray.toJSONString(list)));
		}
		resultMap.success().message(SmsConstants.ResMsg.SET_SUCCESS).dataJson(json);
		return  resultMap;
	}
}
